const jsonData = require("../modify/jsondata.js");
const util = require("../../../utils/util");
const recommendservice = require("../../../apiservice/recommend/recommendservice");
const utils = require("../../../utils/util.js");
const common = require("../modify/common.js");
const app = getApp();
const regeneratorRuntime = app.globalData.regeneratorRuntime;
let userinfo = app.globalData.userInfo;

// pages/promotion/add/add.js
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		genderOpt: jsonData.Gender, //性别选项集
		contentOpt: jsonData.Content, //主要需求选项集
		genderindex: 0, //性别索引
		contentindex: 0, //主要需求索引
		appointmenttothehospitaldate: common.formatTime(new Date(), false), //预约日期
		hospitalList: [], //所有医院列表
		hospitalid: '',
		hospitalindex: 0, //医院索引
		leadName: '', //潜在客户姓名
		telephone: '', //电话
		telephone2: '', //固定电话
		age: '', //年龄
		idnum: '', //身份证
		remark: '', //备注
		doctorid: '', //医生ID
		doctorname: '请选择', //医生名字,

		doctorHospitalid: '',
		birthdate: '请选择', //出生日期
		currDate: utils.frmatDate(new Date()),
    endDate: utils.addDateSeg(new Date().getTime(), "Month", 2, '-')

	},

	/**
	 * 生命周期函数--监听页面加载
	 */

	onLoad: async function(options) {
		if (options) {
			this.setData({
				doctorid: options.contactid ? options.contactid : '',
				doctorname: options.doctorName ? options.doctorName : '请选择',
				doctorHospitalid: options.institutionid ? options.institutionid : ''
			})
		}
    userinfo = app.globalData.userInfo;
    let resultHos = await this.GetAllHospital();
    let hospitalindex = common.getPickerValue(resultHos, userinfo.siteid);
    this.setData({
      hospitalList: resultHos,
      hospitalindex: hospitalindex,
      hospitalid: resultHos[hospitalindex].siteId,
    });
	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: async function() {

	},


	changeGender: function(e) {
		console.log(e);
		this.setData({
			genderindex: e.detail.value

		});
	},
	changeHospital: function(e) {
		console.log(e);
		this.setData({
			hospitalindex: e.detail.value,
			hospitalid: this.data.hospitalList[e.detail.value].siteId,
		});
	},
	changeContent: function(e) {
		console.log(e);
		this.setData({
			contentindex: e.detail.value,
		});
	},
	changeBirthdate: function(e) {
		console.log(e);
		this.setData({
			birthdate: e.detail.value
		})
	},
	changeTelephone2: function(e) {
		console.log(e);
		this.setData({
			telephone2: e.detail
		});
	},
	//监听字段更改
	onChange: function(e) {
		console.log(e);
		var target = e.currentTarget.id;
		if (target == 'new_leadName') {
			this.setData({
				leadName: e.detail
			})
		} else if (target == 'address1_Telephone1') {
			this.setData({
				telephone: e.detail
			})
		} else if (target == 'new_age') {
			this.setData({
				age: e.detail
			})
		} else if (target == 'new_citizenid') {
			this.setData({
				idnum: e.detail
			})
		} else if (target == 'new_remark') {
			this.setData({
				remark: e.detail.value
			})
		} else if (target == 'date') {
			this.setData({
				appointmenttothehospitaldate: e.detail.value
			})
		}
	},
	toSelectDoctor: function() {
		var that = this;
		wx.navigateTo({
			url: "../../doctor/list/list",
			events: {
				openedDoctorPage: function(e) {
					//console.log(e.data)
				},
				DoctorEvent: function(data) {
					console.log(data)
					that.setData({
						doctorid: data.doctorid,
						doctorname: data.doctorname,
						doctorHospitalid: data.hospitalid
					});
				}
			},
			success: function(res) {
				res.eventChannel.emit('openedDoctorPage', {
					data: 'choose'
				})
			}
		})
	},
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {

	},


	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {

	},
	//创建推荐记录
	addRecommond: function(e) {
		//debugger;
		var contentValue = common.getContentValue(this.data.contentindex);
		var recommendobj = {
			new_leadName: this.data.leadName,
			Address1_Telephone1: this.data.telephone,
			new_gender: this.data.genderindex,
			new_age: this.data.age,
			new_citizenid: this.data.idnum,
			new_content: contentValue,
			new_remark: this.data.remark,
			new_hospital: this.data.hospitalid,
			new_appointmenttothehospitaldate: this.data.appointmenttothehospitaldate,
			new_contact: this.data.doctorid,
			new_networkhospitalwherethehospital: this.data.doctorHospitalid,
			new_birthdate: this.data.birthdate,
			telephone2: this.data.telephone2
		};
		var msg = '';
		var isCreate = true;
		var flag = true;
		if (recommendobj.new_leadName.replace(/\s+/g, '') == '' && flag == true) {
			msg = '姓名不能为空';
			isCreate = false;
			flag = false;
		}

    if (recommendobj.Address1_Telephone1 == '' && flag == true) {
        msg = '手机号码不能为空';
        isCreate = false;
        flag = false;
    }

		if (recommendobj.Address1_Telephone1 != '') {
			if (!(/^1[3456789]\d{9}$/.test(recommendobj.Address1_Telephone1)) && flag == true) {
				msg = '手机号码不正确';
				isCreate = false;
				flag = false;
			}
		}
		if (recommendobj.new_age != '') {
			if (recommendobj.new_age > 150) {
				msg = '请填写正确的年龄';
				isCreate = false;
				flag = false;
			}
		}
		if (recommendobj.new_citizenid != '') {
			var idcard_patter =
				/^[1-9][0-9]{5}([1][9][0-9]{2}|[2][0][0|1][0-9])([0][1-9]|[1][0|1|2])([0][1-9]|[1|2][0-9]|[3][0|1])[0-9]{3}([0-9]|[X])$/;
			var idnum = recommendobj.new_citizenid;
			if (!idcard_patter.test(idnum)) {
				msg = '请填写正确的身份证号码';
				isCreate = false;
				flag = false;
			}
		}
		if (recommendobj.new_content == 0 && flag == true) {
			msg = '主要需求不能为空';
			isCreate = false;
			flag = false;
		}

    if (recommendobj.new_hospital == '' && flag == true) {
      msg = '预约医院不能为空';
      isCreate = false;
      flag = false;
    }

		if (recommendobj.new_contact == '' && flag == true) {
			msg = '学术推广医生姓名不能为空';
			isCreate = false;
			flag = false;
		}

		if (this.data.doctorname == '请选择' && flag == true) {
			msg = '学术推广医生姓名不能为空';
			isCreate = false;
			flag = false;
		}



		if (isCreate == false) {
			wx.showToast({
				title: msg,
				icon: 'none',
				duration: 2000
			})
		} else {
			wx.showLoading({
				title: '提交中...',
				mask: true
			})
			this.AddRecommendAndLead(recommendobj);
		}
	},
	//获取所有医院
	GetAllHospital: async function() {
		var result = await recommendservice.GetAllHospital()
		return result.data
	},
	//创建推荐记录
	AddRecommendAndLead: function(recommend) {
		var that = this;
		var appointmenttothehospitaldate = common.formatTime(new Date(), false);
		var hospitalindex = common.getPickerValue(this.data.hospitalList, userinfo.siteid);
    var hospitalId = this.data.hospitalList[hospitalindex].siteId;
		recommendservice.AddRecommendAndLead(recommend).then(function(success) {
			that.showResult(success.data);
			const eventChannel = that.getOpenerEventChannel()
			eventChannel.emit('refreshPage', {
				data: 'test'
			});
			//还原数据
			that.setData({
				leadName: '',
				genderindex: 0, //性别索引
				contentindex: 0, //主要需求索引
				appointmenttothehospitaldate: appointmenttothehospitaldate, //预约日期
        hospitalid: hospitalId,
				hospitalindex: hospitalindex, //医院索引
				leadName: '', //潜在客户姓名
				telephone: '', //电话
				age: '', //年龄
				idnum: '', //身份证
				remark: '', //备注
				doctorid: '', //医生ID
				doctorname: '请选择', //医生名字
				telephone2: '',
				birthdate: ''
			})
		}).catch(function(ex) {
			console.log(ex);
		})
	},
	showResult: function(res) {
		var title = '';
		var icon = '';
		if (res.resultState == 1) {
			title = '创建成功';
			icon = 'success';
		} else {
			title = '创建失败';
			icon = 'none';
		}
		wx.showToast({
			title: title,
			icon: icon,
			duration: 3000
		});
	},
})
